package com.itfitness.checkfaceview

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
    private lateinit var cameraExecutor: ExecutorService
    private var isAnim = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initCamera()
        viewFinder.post {
            val layoutParams = viewFinder.layoutParams
            layoutParams.width = (viewFinder.width / 1.5f).toInt()
            layoutParams.height = (viewFinder.height / 1.5f).toInt()
            viewFinder.layoutParams = layoutParams
        }
        checkView.setOnClickListener {
            if(isAnim){
                checkView.pauseAnim()
            }else{
                checkView.resumeAnim()
            }
            isAnim = !isAnim
        }
    }

    private fun initCamera(){
        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }
    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(viewFinder.surfaceProvider)
                }
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraExecutor.shutdown()
    }
}